<template>
  <div class="generate-cover">
    <el-space wrap>
      <c-select
        width="160px"
        v-model="image_type"
        prefixText="类型："
        :loading="typeLoading"
        :optionList="typeGroupData"
        @change="onImageTypeChange"
      ></c-select>
      <c-select
        v-if="activeTab == 2"
        width="120px"
        v-model="cover_size"
        prefixText="尺寸："
        :optionList="[
          { label: '9:16', value: 1 },
          { label: '3:4', value: 2 },
          { label: '2:3', value: 3 },
        ]"
      ></c-select>
      <c-select
        v-if="activeTab == 2"
        width="120px"
        v-model="column_num"
        prefixText="列数："
        :optionList="[
          { label: '2列', value: 2 },
          { label: '3列', value: 3 },
          { label: '4列', value: 4 },
          { label: '5列', value: 5 },
        ]"
      ></c-select>
      <el-button type="primary" @click="hanleModal" v-if="list.length">选择当前</el-button>
      <el-button type="primary" @click="hanleCommonModal">选择素材</el-button>
      <el-upload
        multiple
        :show-file-list="false"
        :accept="['image/*'].join(',')"
        :before-upload="beforeUpload"
        :http-request="initHttpRequest"
      >
        <el-button type="primary">选择本地</el-button>
      </el-upload>
    </el-space>

    <!-- <el-divider border-style="dashed" /> -->

    <div class="cover-box">
      <el-tabs v-model="activeTab" @click="onTabChange">
        <el-tab-pane label="公众号封面" :name="1"> </el-tab-pane>
        <el-tab-pane label="短视频封面" :name="2"> </el-tab-pane>
      </el-tabs>

      <cover-weixin-h5
        v-if="activeTab == 1"
        :imageType="image_type"
        :list="virtualCheckItems"
        :groupList="typeGroupData"
      ></cover-weixin-h5>
      <cover-short-video
        v-if="activeTab == 2"
        :imageType="image_type"
        :list="virtualCheckItems"
        :groupList="typeGroupData"
        :coverSize="cover_size"
        :columnNum="column_num"
      ></cover-short-video>
    </div>
  </div>

  <c-dialog
    title="选择当前图像"
    :width="globalStore.device.type == 'desktop' ? '1000' : '90%'"
    name="select-cur-image-popup"
  >
    <div class="select-cur-image-popup">
      <virtual-scroll-grid
        :itemSize="150"
        :rowCount="globalStore.device.type == 'desktop' ? 5 : 4"
        height="62vh"
        :items="virtualItems"
        keyField="_id"
        v-model:checkItems="checkItems"
      ></virtual-scroll-grid>
      <div class="dialog-footer">
        <el-button plain @click="handleCancel"> 取 消 </el-button>
        <el-button type="primary" @click="handleConfirm"> 确 定 </el-button>
      </div>
    </div>
  </c-dialog>

  <c-dialog
    title="选择素材图像"
    :width="globalStore.device.type == 'desktop' ? '1200' : '90%'"
    name="select-com-image-popup"
  >
    <select-image-popup
      isCommon
      :userType="userType"
      :imageType="image_type"
      v-model="virtualCheckItems"
      :rowCount="globalStore.device.type == 'desktop' ? 5 : 4"
      @on-end="onSelectImageEnd"
    ></select-image-popup>
  </c-dialog>
</template>

<script setup>
import { ref, computed, nextTick, watch } from 'vue';
import { allTypeGroup, userListGroup } from '@/apis/user';
import { useFetch } from '@/hooks/useFetch/index.js';
import SelectImagePopup from '@/components/select-image-popup/index.vue';
import virtualScrollGrid from '@/components/virtual-scroll/virtual-scroll-grid.vue';
import { v4 } from 'uuid';
import { usePhoneCanvas } from '@/hooks/usePhoneCanvas/index.js';
import dayjs from 'dayjs';
import { fileFormUrl } from '@/utils/tools.js';
import CoverWeixinH5 from './cover-weixin-h5.vue';
import CoverShortVideo from './cover-short-video.vue';

import { useGlobalStore } from '@/pinia/modules/global';
const globalStore = useGlobalStore();

// store modal
import { useModalStore } from '@/pinia/modules/modal';
const modalStore = useModalStore();

const props = defineProps({
  list: {
    type: Array,
    default: () => [],
  },

  // 0 普通用户 1 admin
  userType: {
    type: [String, Number],
    default: 0,
  },
});

const { loading: typeLoading, data: typeGroupData } = useFetch({
  api: props.userType == 1 ? allTypeGroup : userListGroup,
});

const activeTab = ref(1);

const contentRef = ref();

const image_type = ref(1);

const cover_size = ref(1);

const column_num = ref(3);

const temp_type = ref(1);

const virtualCheckItems = ref([]);

const checkItems = ref([]);

const virtualItems = computed(() => {
  console.log(props.list, 'props.list');

  return props.list.map((v) => {
    return {
      ...v,
      _id: v4(),
      images: [{ url: v.imgUrl }],
    };
  });
});

const onSelectImageEnd = (list) => {
  console.log(list, 'list');
  virtualCheckItems.value = list.map((v) => {
    return { ...v, imgUrl: v.images[0].url };
  });
};

const hanleCommonModal = () => {
  modalStore.openModal('select-com-image-popup');
};

const beforeUpload = () => {};

const initHttpRequest = async (options) => {
  const file = options.file;
  const imgUrl = fileFormUrl(file);
  virtualCheckItems.value.push({
    imgUrl: imgUrl,
    images: [{ url: imgUrl }],
    _id: v4(),
  });
  console.log(options, 'options---');
};

const hanleModal = () => {
  checkItems.value = virtualCheckItems.value;

  console.log(checkItems.value, 'checkItems.value');

  console.log(virtualItems.value, 'virtualItems.value');

  modalStore.openModal('select-cur-image-popup');
};

const handleCancel = () => {
  modalStore.closeModal('select-cur-image-popup');
};

const handleConfirm = () => {
  virtualCheckItems.value = checkItems.value;
  handleCancel();
};

const initImageData = async () => {
  for (const item of virtualCheckItems.value) {
    console.log(item, 'item');

    item['isWHCan'] = await isWH(item.imgUrl);

    if (image_type.value == 1) {
      const { toDataURL } = usePhoneCanvas({ imgUrl: item.imgUrl });
      let phoneImgUrl = await toDataURL();
      console.log(phoneImgUrl, 'toDataURL');
      item['phoneImgUrl'] = phoneImgUrl;
    }
  }
};

const onImageTypeChange = () => {
  initImageData();
};

const calcImageSize = (url) => {
  return new Promise((resolve, reject) => {
    let image = document.createElement('img');
    image.src = url;
    image.onload = () => resolve({ width: image.width, height: image.height });
    image.onerror = reject;
  });
};

const isWH = async (url) => {
  const { width, height } = await calcImageSize(url);
  console.log(width, height, 'width, height', width > height);

  return width >= height;
};

const onTabChange = (e) => {
  console.log(e, activeTab.value, 'activeTab');

  if (activeTab.value == 2) {
    image_type.value = 1;
  }
};

watch(
  () => virtualItems.value,
  () => {
    virtualCheckItems.value = virtualItems.value.slice(0, 4);
    console.log(virtualItems.value.slice(0, 4), 'virtualItems.value.slice(0, 4)');
  },
  { deep: true },
);

watch(
  () => virtualCheckItems.value,
  async () => {
    initImageData();
  },
  { deep: true },
);
</script>

<style lang="scss" scoped>
.generate-cover {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.cover-box {
  padding: 5px;
  box-sizing: border-box;
  margin-top: 5px;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}
</style>

<style lang="scss"></style>
